package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {
    @Override
    public ResponseResult listByName(ChannelDto dto) {

        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
//        LambdaQueryWrapper<WmChannel> queryWrapper = Wrappers.lambdaQuery();

//        判断dto中的name是否为空
        if (StringUtils.isNotBlank(dto.getName())) {
  //       名称  模糊查询
            queryWrapper.like(WmChannel::getName,dto.getName());
        }
//       分页
        IPage<WmChannel> page = new Page<>(dto.getPage(),dto.getSize());  //long current, long size
        IPage<WmChannel> page1 = this.page(page, queryWrapper);

        return new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal(),page1.getRecords());// Long currentPage, Integer size, Long total, T data
    }

    @Override
    public ResponseResult saveWmChannel(WmChannel wmChannel) {
//        在新增之前根据name判断是否已经存在
//        判断的方式就是先根据name查询，看是否能查到
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName,wmChannel.getName());
        WmChannel one = this.getOne(queryWrapper);
        if(one==null){
//            如果查不到再新增
            this.save(wmChannel);
            return ResponseResult.okResult();
        }else{ // 如果查到了 返回一个错误提示
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

    }
}
